package com.kfm.servlet;

import com.kfm.service.FileService;
import com.kfm.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig(maxFileSize = 1024 * 1024 * 5, location = "d:\\temp")
public class UploadServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        // 判断是否登录
        if (! LoginUtil.isLogin(getServletContext())){
            response.sendRedirect("login");
            return;
        }
        req.getRequestDispatcher("WEB-INF/upload.html").forward(req, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取上传的文件对象
        Part part = request.getPart("file");

        if (part != null) {
            FileService fileService = new FileService();

            int result = fileService.save(part.getInputStream(), part.getSubmittedFileName(), part.getSize());

            if (result > 0){
                response.sendRedirect("index.html");
                return;
            }
        }
        response.sendRedirect("upload.html");
    }
}
